package org.spider.core.job;

import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spider.api.domain.model.SpiderFlow;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 本定时任务管理器使用Quartz的定时器。因为spring提供的定时器需要自己维护按key查找的功能
 * @author djj
 */
@Component
public class SpiderJobManager {
    private static Logger logger = LoggerFactory.getLogger(SpiderJobManager.class);

    public final static String JOB_NAME = "SPIDER_TASK_";

    public final static String JOB_PARAM_NAME = "FLOW";

    @Resource
    private Scheduler scheduler;

    /**
     * @param flow
     * @return 下次执行时间
     */
    public Date addJob(SpiderFlow flow){
        try {
            //描述任务内容
            JobDetail jobDetail = JobBuilder.newJob(SpiderJob.class)  //指定Job的实现类，调用接口
                    .withIdentity(getJobKey(flow.getId()))
                    .build();
            jobDetail.getJobDataMap().put(JOB_PARAM_NAME,flow); //后续执行需要,保存在map中
            //描述触发机制
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(flow.getCron())
                    .withMisfireHandlingInstructionDoNothing(); //超时不处理

            CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                    .withIdentity(getTriggerKey(flow.getId()))
                    .withSchedule(cronScheduleBuilder)
                    .build();
            return scheduler.scheduleJob(jobDetail,cronTrigger);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean remove(String id){
        JobKey jobKey = getJobKey(id);
        try {
            return scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            return false;
        }
    }

    public boolean exists(String id){
        try {
            return scheduler.checkExists(getJobKey(id));
        } catch (SchedulerException e) {
            return false;
        }
    }


    private JobKey getJobKey(String id){
        return JobKey.jobKey(JOB_NAME+id);
    }

    private TriggerKey getTriggerKey(String id){
        return TriggerKey.triggerKey(JOB_NAME+id);
    }

}
